<template>
  <div class="userEditor">
    <maynav
      :title="titleObj[type]"
      :path="path"
      :right="right"
      @click.native="save"
    ></maynav>
    <div class="content">
      <van-field
        v-model="inputValue"
        v-if="type !== 'photo'"
        class="field"
        placeholder="请输入用户名"
      />
      <van-uploader
        v-else
        v-model="list"
        max-count="1"
        :before-read="beforeRead"
      ></van-uploader>
    </div>
  </div>
</template>

<script>
// 引入mapState
import { mapState } from 'vuex'
import { userProfile } from '@/api/user.js'
export default {
  computed: {
    ...mapState(['userInfo'])
  },
  data () {
    return {
      inputValue: '',
      type: this.$route.query.type,
      path: '/home/userInfo',
      right: '',
      disPic: '',
      list: [],
      titleObj: {
        name: '修改昵称',
        gender: '修改性别',
        birthday: '修改生日',
        photo: '修改头像'
      }
    }
  },
  methods: {
    // 保存
    save () {
      if (this.right === '') {
        return
      }
      this.userEditor({
        [this.type]: this.inputValue
      })
    },
    // 编辑用户信息
    userEditor (obj) {
      userProfile(obj).then(() => {
        this.$toast.success('编辑成功')
        this.$router.push(this.path)
        // 更新到vuex当中
        this.$route.dispatch('reUsreInfo')
      })
    },
    // 上传前
    beforeRead (file) {
      const isImg =
        file.type === 'image/png' ||
        file.type === 'image/jpg' ||
        file.type === 'image/gif'
      const limit2M = file.size / 1024 / 1024 < 2
      if (!isImg) {
        this.$toast.fail('请上传带jpeg|png|gif格式图片')
      }
      if (!limit2M) {
        this.$toast.fail('请小于2M的带jpeg|png|gif格式图片')
      }
      return isImg && limit2M
    },
    // 上传后
    async afterRead (file) {
      // 创建new FormData
      const _formData = new FormData()
      _formData.append('files', file.file)
      // 调用上传api
      //   const res = await upload(_formData)
      //   window.console.log('上传成功', res)
      //   this.inputValue = res.data.data[0].id
    }
  },
  watch: {
    inputValue (newVal) {
      if (newVal !== this.userInfo[this.type] && newVal !== '') {
        this.right = '保存'
      } else {
        this.right = ''
      }
    }
  }
}
</script>

<style lang="less">
.userEditor {
  // background-image: url(~@/assets/moto.jpg);
  .content {
    padding: 20px @p15;
    text-align: center;
    .field {
      background-color: #937f9e;
      border-radius: 10px;
    }
  }
}
</style>
